package com.pku.control;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.lang.reflect.Type;
import java.util.ArrayList;

public class MemoryFragment extends Fragment {
    private String maccode;
    private LineChart chart;
    private int blue = Color.parseColor("#9932CD");
    private ArrayList<Entry> values;
    private TextView total_memory_size,available_size,memory_usage,spare_size,swap_memory_total,swap_used_percent,swap_memory_usage,
            swap_spare_size,swap_sin,swap_sout;
    private Handler handler = new Handler();
    public MemoryFragment(String maccode) {
        this.maccode = maccode;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mem, container,false);
        chart = view.findViewById(R.id.chart);
        total_memory_size=view.findViewById(R.id.total_memory_size);
        available_size=view.findViewById(R.id.available_size);
        memory_usage=view.findViewById(R.id.memory_usage);
        spare_size=view.findViewById(R.id.spare_size);
        swap_memory_total=view.findViewById(R.id.swap_memory_total);
        swap_used_percent=view.findViewById(R.id.swap_used_percent);
        swap_memory_usage=view.findViewById(R.id.swap_memory_usage);
        swap_spare_size=view.findViewById(R.id.swap_spare_size);
        swap_sin=view.findViewById(R.id.swap_sin);
        swap_sout=view.findViewById(R.id.swap_sout);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        chart.setBackgroundColor(Color.WHITE);
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(false);
        chart.setDrawGridBackground(false);


        // enable scaling and dragging
        chart.setDragEnabled(false);
        chart.setScaleEnabled(false);
        chart.setPinchZoom(false);
        chart.setDrawBorders(true);
        chart.setBorderWidth(2f);
        chart.setBorderColor(blue);

        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);//取消x轴网格
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴在底部显示
        xAxis.setAxisLineWidth(2f);
        xAxis.setAxisLineColor(blue);//y轴线颜色
        xAxis.setAxisMaximum(60f);
        xAxis.setAxisMinimum(0f);
        IAxisValueFormatter valueFormatter = new IAxisValueFormatter() {


            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "";
            }
        };
        xAxis.setValueFormatter(valueFormatter);//设置自定义格式，在绘制之前动态调整x的值。


        YAxis yAxis = chart.getAxisLeft();
        yAxis.setDrawGridLines(true);
        yAxis.setGridColor(blue);
        yAxis.setGridLineWidth(1f);
        yAxis.setAxisLineWidth(2f);
        yAxis.setTextColor(blue);
        yAxis.setAxisLineColor(Color.parseColor("#229932CD"));//y轴线颜色
        chart.getAxisRight().setEnabled(false);
        yAxis.setAxisMaximum(100f);
        yAxis.setAxisMinimum(0f);
        IAxisValueFormatter valueFormatters = new IAxisValueFormatter() {


            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) value + "%";
            }
        };
        yAxis.setValueFormatter(valueFormatters);//设置自定义格式，在绘制之前动态调整x的值。
        setData();
        initData();
        chart.animateX(500);
    }
    private void initData() {
        String url = "http://8.131.87.108:9000/api";
        OkGo.<String>post(url).params("hardwarecode", "memory").params("maccode", maccode).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.d("victory", "列表为:" + response.body());
                String body = response.body();
                if (body != null) {
                    Gson gson = new Gson();
                    Type type = new TypeToken<MemoryInfo>() {
                    }.getType();
                    MemoryInfo info = gson.fromJson(response.body(), type);
                    total_memory_size.setText("总内存:"+info.getTotal_memory_size()+"G");
                    available_size.setText("内存可用量:"+info.getAvailable_size()+"G");
                    memory_usage.setText("内存使用量:"+info.getMemory_usage()+"G");
                    spare_size.setText("内存剩余量:"+info.getSpare_size()+"G");
                    swap_memory_total.setText("总虚拟内存:"+info.getSwap_memory_total()+"G");
                    swap_used_percent.setText("虚拟内存使用率:"+info.getSwap_used_percent()+"%");
                    swap_memory_usage.setText("虚拟内存使用量:"+info.getSwap_memory_usage()+"G");
                    swap_spare_size.setText("虚拟内存剩余量:"+info.getSwap_spare_size()+"G");
                    swap_sin.setText("系统已从磁盘交换入的大小:"+info.getSwap_sin()+"G");
                    swap_sout.setText("系统已从磁盘交换出的大小:"+info.getSwap_sout()+"G");




                    float val=0;
                    try {
                        val = Float.parseFloat(info.getUsed_percent());
                    } catch (NumberFormatException e) {
                        val=0;
                        e.printStackTrace();
                    }
                    if (values.size() >= 60) {
                        LineData lineData = chart.getData();
                        LineDataSet set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
                        lineData.removeDataSet(lineData.getDataSetCount() - 1);
                        values.clear();
                        values.add(new Entry(0, val));
                        set1 = new LineDataSet(values, "DataSet 1");
                        set1.setLabel("内存利用率");
                        set1.setDrawIcons(false);
                        set1.setDrawCircles(false);
                        set1.setColor(blue);
                        set1.setDrawValues(false);
                        set1.setLineWidth(2f);
                        set1.setDrawCircleHole(false);
                        set1.setDrawFilled(true);
                        if (Utils.getSDKInt() >= 18) {
                            Resources resources = getContext().getResources();
                            Drawable drawable = resources.getDrawable(R.drawable.fade_zise);
                            // drawables only supported on api level 18 and above
                            //Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_zise);
                            set1.setFillDrawable(drawable);
                        } else {
                            set1.setFillColor(Color.BLACK);
                        }
                        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
                        dataSets.add(set1);
                        LineData data = new LineData(dataSets);
                        chart.setData(data);
                    } else {
                        int size = values.size();
                        values.add(new Entry(size, val));
                        chart.invalidate();
                    }
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initData();
                        }
                    }, 2000);//2秒后执行Runnable中的run方法
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    private void setData() {
        values = new ArrayList<>();
        values.add(new Entry(0, 18));
        LineDataSet set1;
        set1 = new LineDataSet(values, "DataSet 1");
        set1.setLabel("内存利用率");
        set1.setDrawIcons(false);
        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setColor(blue);
        set1.setLineWidth(2f);
        set1.setDrawCircleHole(false);
        set1.setDrawFilled(true);
        if (Utils.getSDKInt() >= 18) {
            Resources resources = getContext().getResources();
            Drawable drawable = resources.getDrawable(R.drawable.fade_zise);
           // Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.fade_zise);
            set1.setFillDrawable(drawable);
        } else {
            set1.setFillColor(Color.BLACK);
        }
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);
        LineData data = new LineData(dataSets);
        chart.setData(data);
    }
}
